Thumb

Extension Methods?

1/12/2020 1:49:58 AM

Extension method allow to add new method in existing class. When we call the extension method, we can’t create the instance of the class and also, we can’t pass the argument. If we want to pass the argument but it can’t essential. We need to class and method static and just use this key word in pass the argument then we create extension method. Given the example code of the extension method:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObjectTest
{
    public static class Student
    {
        public static string FirstLetterUpper(this string myStr)
        {
            if (myStr.Length>0)
            {
                char[] charArray = myStr.ToCharArray();
                charArray[0] = char.IsUpper(charArray[0]) ? char.ToLower(charArray[0]) : char.ToUpper(charArray[0]);
                return new string(charArray);
            }
            return myStr;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string str = "sakib";
            string result = str.FirstLetterUpper();
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

We can see the Student class contain FirstLetterUpper method. This method argument uses this key word and also this method use by non-argument pass Program class. We can call   FirstLetterUpper method is extension method.